<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div v-loading="pageLoading" class="reimbursement-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="baseInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" :style="`${showMobilePage?'margin: 0':''}`" @queryProcessData="queryProcessData"/>
        <div class="reimbursement-detail-content small-padding">
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
          <!--基础信息-->
          <BaseDetailInfo :base-info="baseInfo" :is-edit-date="!!canEditPlanPaymentDate" @editPlanPaymentDate="editPlanPaymentDate" />
          <!--收款账户-->
          <AccountTable ref="accountTableRef" :log-text-header="baseInfo.approvalNo" :is-edit="false" :is-completed="isCompleted || isRevoke" />
          <!--常规报销-->
          <CommonProject
            v-if="baseInfo.type === 0"
            ref="commonProjectRef"
            v-model="baseInfo.totalReimbursementAmount"
            :show-extend-btn="showExtendBtn"
            :is-edit="false"
            :is-current-version="isCurrentVersion"
            @freshData="initData"
            @extendEvent="editDescDialogOpen($event, 0)"
          />
          <!--差旅报销-->
          <TravelProject v-if="baseInfo.type === 1" ref="travelProjectRef" v-model="baseInfo.totalReimbursementAmount" :is-edit="false" />
          <!--费用分摊-->
          <AllocationTable
            v-if="baseInfo.isAllocation === 1"
            ref="allocationTableRef"
            v-model="baseInfo.totalAllocationAmount"
            :show-extend-btn="showExtendBtn"
            :is-edit="false"
            @extendEvent="editDescDialogOpen($event, 1)"
          />
          <!--关联审批-->
          <AssociatedApproval ref="associatedApprovalRef" :is-edit="false" style="margin-top: 28px;" />
        </div>
        <ExamineAndApprove
          ref="examineAndApproveRef"
          :show-print="true"
          :version="version"
          :print-data="baseInfo"
          :disabled="pageLoading"
          :process-id="processId"
          :main-id="reimbursementId"
          :get-comments-api="getReimbursementComments"
          :comment-add-api="reimbursementCommentAdd"
          :process-revocation-api="reimbursementProcessRevocation"
          :process-recall-api="reimbursementProcessRecall"
          :process-audit-api="reimbursementProcessAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.REIMBURSEMENT"
          :process-type="PROCESS_TYPE.REIMBURSEMENT"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[{id: baseInfo.proposerId, userName: baseInfo.proposer}]"
          :approval-module-type="APPROVAL_MODULE_TYPE.REIMBURSEMENT"
          :is-apply="isApply"
          next-approve-module-id="reimbursementId"
          redirect-url="/businessPage/reimbursementDetail"
          detail-page-router-name="reimbursementDetail"
          edit-page-router-name="reimbursementEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handlePressSend="handlePressSend"
          @handleCreateNew="handleCreateNew"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('reimbursementEdit',{id: reimbursementId},{remodifyId: processId})"
          @getHistoryDetail="getHistoryDetail"
          @setCurrentVersion="setCurrentVersion"
          @freshDetail="queryInfo"
          @handleCancelPress="handleCancelPress"
        />
      </template>
      <DeniedPlaceholder v-else />
      <EditDescDialog
        ref="editDescDialog"
        v-model="currEditDescContent"
        @handleDescEdit="handleDescEdit"
      />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/businessPage/reimbursementDetail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
    </div>
  </div>
</template>
<script>
// 组件
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import Title from '@/components/Title';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import EditDescDialog from './module/editDescDialog';
import BaseDetailInfo from './module/baseDetailInfo';
import AccountTable from '../module/accountTable';
import CommonProject from '../module/commonProject';
import TravelProject from '../module/travelProject';
import AllocationTable from '../module/allocationTable';
import AssociatedApproval from '../module/associatedApproval';
// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { hasRouteAuth } from '@/utils/permission';
import { BUSINESS_TYPE, PROCESS_TYPE } from '@/utils/const/process';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';

// API
import {
  getReimbursementDetail,
  reimbursementProcessRecall,
  reimbursementProcessRevocation,
  reimbursementProcessAudit,
  editReimbursementDesc,
  reimbursementCommentAdd,
  getReimbursementComments
} from '@/api/reimbursement';
import { planPaymentDateEdit } from '@/api/common';
import schedule from '@/mixins/schedule';
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import { FIXED_PROCESS_TYPE, EVENT_TYPE } from '@/utils/const/process';

export default {
  components: {
    EditDescDialog,
    BaseDetailInfo,
    AccountTable,
    CommonProject,
    TravelProject,
    AllocationTable,
    AssociatedApproval,
    ProgressStep,
    Title,
    explanation,
    ExamineAndApprove
  },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE,
      revokeImg,
      BUSINESS_TYPE,
      PROCESS_TYPE,
      PROGRESS_STEP,
      // api
      reimbursementProcessRevocation,
      reimbursementCommentAdd,
      getReimbursementComments,
      reimbursementProcessRecall,
      reimbursementProcessAudit,
      permissionDenied: false, // 详情页是否可查看
      reimbursementId: '', // 报销单id
      processId: '', // 流程id
      currEditDescContent: '', // 编辑说明当前内容
      currEditDescId: '', // 编辑说明当前id
      currEditDescType: null, // 编辑说明对象 - 0：常规，1：分摊
      baseInfo: { },
      processData: {},
      pageLoading: false,
      stepActiveId: PROGRESS_STEP.PENDING,
      isRevoke: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    createUser() {
      let user = { id: this.baseInfo.creatorId, userName: this.baseInfo.creator };
      if (this.userInfo.id === this.baseInfo.creatorId) {
        user = this.userInfo;
      }
      return user;
    },
    showExtendBtn() {
      const { isApprover, editDescEventIsOpen } = this.baseInfo;
      return isApprover && editDescEventIsOpen && this.isCurrentVersion;
    },
    canEditPlanPaymentDate() { // 是否可编辑计划支付日期
      const { isApprover } = this.baseInfo;
      const eventList = this.processData.operation && this.processData.operation.setEvents || [];
      return isApprover && eventList.includes(EVENT_TYPE.OPEN_PAY_TIME) && !this.isCompleted && this.isCurrentVersion;
    },
    isCompleted() { // 审批已完成
      return this.stepActiveId === PROGRESS_STEP.FINISHED;
    },
    isApply() { // 申请人
      const proposerId = this.baseInfo && this.baseInfo.proposerId ? this.baseInfo.proposerId : '';
      return proposerId && this.userInfo.id === proposerId;
    }
  },
  created() {
    this.initData();
  },
  mounted() {
    if (this.$route.query.openComment) {
      this.$refs['examineAndApproveRef'].isShowProcess = true;
    }
  },
  methods: {
    hasRouteAuth,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.reimbursementId = this.$route.query.reimbursementId;
      this.processId = this.$route.query.processId;
      if (!this.reimbursementId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    // 回填表单数据
    setFormData(data) {
      this.$nextTick(() => {
        this.baseInfo.totalReimbursementAmount = (+data.totalReimbursementAmount).toFixed(2);
        this.baseInfo.totalAllocationAmount = (+data.totalAllocationAmount).toFixed(2);
        this.$refs['accountTableRef'].setTableData(data.accountInfo);
        this.$refs['associatedApprovalRef'].setTableData(data.approvalList);
        if (this.baseInfo.isAllocation === 1) {
          this.$refs['allocationTableRef'].setTableData(data.allocationList);
        }
        if (this.baseInfo.type === 0) {
          this.$refs['commonProjectRef'].setTableData(data.commonProjectList);
        } else {
          this.$refs['travelProjectRef'].setTableData(data.travelProjectList);
        }
      });
    },
    // 获取基本信息
    queryInfo() {
      this.pageLoading = true;
      getReimbursementDetail(this.reimbursementId).then(res => {
        this.handleProcessCheck(res.data.processId);
        this.handleDetailData(res);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.pageLoading = false;
      });
    },
    // 处理详情接口返回的数据
    handleDetailData(res) {
      this.pageLoading = false;
      if (res.code === 200) {
        this.baseInfo = res.data;
        this.setFormData(res.data);
        this.commentCount = res.data.commentCount;
        if (res.data.processStatus === 3) { // 3为撤销
          this.stepActiveId = PROGRESS_STEP.PENDING;
          this.isRevoke = true;
        } else {
          this.stepActiveId = res.data.processStatus;
          this.isRevoke = false;
        }
      }
    },
    queryProcessData() {
      this.queryInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs['examineAndApproveRef'] && this.$refs['examineAndApproveRef'].getProcessList();
      });
    },
    editDescDialogOpen(extendData, type) {
      this.currEditDescType = type;
      this.currEditDescContent = extendData.desc;
      this.currEditDescId = extendData.id;
      this.$refs['editDescDialog'].dialogVisible = true;
    },
    // 编辑说明
    handleDescEdit() {
      const params = {};
      params.type = this.currEditDescType;
      params.descId = this.currEditDescId;
      params.desc = this.currEditDescContent;
      this.pageLoading = true;
      editReimbursementDesc(params).then(res => {
        this.pageLoading = false;
        this.$message.success('编辑成功');
        res.code === 200 && this.initData();
      }).catch(_ => {
        this.pageLoading = false;
      });
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'reimbursement' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    setProcessData(processData) {
      this.processData = processData;
    },
    // 计划支付日期编辑
    editPlanPaymentDate(val, type) {
      const params = {};
      params.id = this.reimbursementId;
      params.moduleType = FIXED_PROCESS_TYPE.REIMBURSEMENT;
      if (type === 'plan') {
        params.planPaymentDate = val;
        params.actualPaymentDate = this.baseInfo.actualPaymentDate;
      } else {
        params.planPaymentDate = this.baseInfo.planPaymentDate;
        params.actualPaymentDate = val;
      }
      planPaymentDateEdit(params).then(res => {
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.queryInfo();
        }
      });
    },
    // 再次发起（复制）新打开页面
    handleCreateNew() {
      const routeUrl = this.$router.resolve({
        name: 'reimbursementEdit',
        params: { id: this.reimbursementId },
        query: { reapplyId: this.processId, createNew: 1 }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.reimbursement-detail-container{
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
  .reimbursement-detail-content{
    position: relative;
    padding: 16px 24px 56px;
  }
  &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
}
::v-deep .el-drawer {
  min-width: 300px;
}
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
.mobile-detail-wrap {
  .reimbursement-detail-content {
    padding-top: 12px !important;
  }
}
</style>
